package com.hyou.springboot.validator.constraints;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

import org.apache.commons.lang3.StringUtils;

import com.hyou.springboot.annotation.validator.EnumRange;

/**
 * <pre>
 * 枚举性质的数据取值范围校验器
 *
 * 校验给定的值value是否是指定取值范围range中的值
 * </pre>
 *
 * @author FengChangshuo
 * @version 1.0.0 2018-03-28 11:03:33 初始创建
 */
public class EnumRangeValidator implements ConstraintValidator<EnumRange, String> {

    private String[] range;

    @Override
    public void initialize(EnumRange constraintAnnotation) {
        this.range = constraintAnnotation.range();
    }

    @Override
    public boolean isValid(String value, ConstraintValidatorContext context) {

        if (StringUtils.isBlank(value)) {
            return true;
        }

        String[] values = value.split(",");
        int success = 0;
        for (String rangeItem : range) {
            for (String valueItem : values) {
                if (valueItem.equals(rangeItem)) {
                    success++;
                }
            }
        }
        return success == values.length;
    }

}
